// 云函数模板
// 部署：在 cloud-functions/login 文件夹右击选择 “上传并部署”

const cloud = require('wx-server-sdk')

// 初始化 cloud
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})

Date.prototype.Format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份 
    "d+": this.getDate(), //日 
    "H+": this.getHours(), //小时 
    "m+": this.getMinutes(), //分 
    "s+": this.getSeconds(), //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds() //毫秒 
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

/**
 * 这个示例将经自动鉴权过的小程序用户 openid 返回给小程序端
 * 
 * event 参数包含小程序端调用传入的 data
 * 
 */
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  let openid = wxContext.OPENID;
  const db = cloud.database();
  try {
    let getResult = await db.collection('users').where({
      openid: openid,
    }).get();
    console.log(getResult);
    if (getResult.data.length == 0) {
      console.log('login new user openid ' + openid);
      let addResult = await db.collection('users').add({
        data: {
          openid: openid,
          createdAt: new Date(),
        }
      });
    }
    return {
      code: 0,
      msg: 'success',
      data: {
        openid: wxContext.OPENID,
        //event,
        //appid: wxContext.APPID,
        //unionid: wxContext.UNIONID,
        //env: wxContext.ENV,
      }
    }
  } catch (e) {
    console.log('login query user catch exception openid ' + openid + ' err ' + e);
    return {
      code: 1,
      msg: 'error',
      data: {
        //event,
        //openid: wxContext.OPENID,
        //appid: wxContext.APPID,
        //unionid: wxContext.UNIONID,
        //env: wxContext.ENV,
      }
    }
  }
}